package ua.edu.nuos.tees.jdmmon.gui.components;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * Percent indicator for power indicating
 *
 * @author Olha Mudrievska
 *         12.05.13
 */
public class ScaleIndicator extends JPanel {

    private BufferedImage backgroundImage = null;
    private JLabel digitalIndicator;
    private double value;
    private long endValue;

    public ScaleIndicator(URL imageUrl, long endValue){
        digitalIndicator = new JLabel();
        setLayout(new GridBagLayout());
        setImage(imageUrl);
        this.endValue = endValue;
        addDigitalIndicator("0");
    }

    private void addDigitalIndicator(String initialText){
        GridBagConstraints gbc = new GridBagConstraints();
        digitalIndicator.setOpaque(true);
        digitalIndicator.setForeground(Color.WHITE);
        digitalIndicator.setBackground(new Color(70, 70, 70));
        digitalIndicator.setHorizontalAlignment(SwingConstants.RIGHT);
        digitalIndicator.setFont(new Font("Arial", Font.BOLD, 16));
        digitalIndicator.setText(initialText);
        gbc.weighty = 1.0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.PAGE_START;
        gbc.insets = new Insets(502, 0, 0, 0);
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(digitalIndicator, gbc);
    }

    /**
     * Set background image
     * @param imageUrl image URL address
     */
    public void setImage(URL imageUrl) {
        try {
            backgroundImage = ImageIO.read(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * Set current value
     * @param value value
     */
    public void setValue(double value) {
        this.value = (120 * value / endValue);
        digitalIndicator.setText(String.valueOf(String.format("%8.2f", this.value).replace(',', '.')));
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        int xShift = (this.getWidth() - backgroundImage.getWidth()) / 2;
        int yShift = 5;
        super.paintComponent(g);
        g.drawImage(backgroundImage, xShift, yShift, null);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawImage(backgroundImage, xShift, yShift, null);
        g2d.setStroke(new BasicStroke(2));
        g2d.setColor(new Color(128, 0, 0));

        for (int i = 0; i < 10; i += 2) {
            g2d.draw(new Line2D.Float(22 + i + xShift, 483 + yShift,
                    22 + i + xShift, 483 + yShift - ((float) ((value * 443) / 120))));
        }
    }
}